# -*- coding:utf-8 -*-
from django.db.models.sql import compiler
from django.utils.six.moves import zip_longest


"""
    mysql模块具体相关的编译器compiler
    基础的编译器，继承自sql模块中的compiler文件中
    仅仅是自定义了两个接口resolve_columns和as_subquery_condition
"""
class SQLCompiler(compiler.SQLCompiler):
    """
        分解行数
    """
    def resolve_columns(self, row, fields=()):
        values = []
        index_extra_select = len(self.query.extra_select)
        for value, field in zip_longest(row[index_extra_select:], fields):
            if (field and field.get_internal_type() in ("BooleanField", "NullBooleanField") and
                value in (0, 1)):
                value = bool(value)
            values.append(value)
        return row[:index_extra_select] + tuple(values)

    """

    """
    def as_subquery_condition(self, alias, columns, qn):
        qn2 = self.connection.ops.quote_name
        sql, params = self.as_sql()
        return '(%s) IN (%s)' % (', '.join(['%s.%s' % (qn(alias), qn2(column)) for column in columns]), sql), params


#  insert的编译器，继承自两个父类
class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
    pass


# delete的编译器，继承自两个父类
class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
    pass


# update的编译器
class SQLUpdateCompiler(compiler.SQLUpdateCompiler, SQLCompiler):
    pass


# 集合的
class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler):
    pass


# date的
class SQLDateCompiler(compiler.SQLDateCompiler, SQLCompiler):
    pass


# datetime的
class SQLDateTimeCompiler(compiler.SQLDateTimeCompiler, SQLCompiler):
    pass
